import * as THREE from 'three'
import { FontLoader } from 'three/examples/jsm/loaders/FontLoader.js'
import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry.js'
import fontTyoe from 'three/examples/fonts/helvetiker_regular.typeface.json'
import createApp from '../../core'
import { MeshNormalMaterial } from 'three'

function createTextGeometry (dom: HTMLElement) {
  const { camera, scene, update, gui } = createApp(dom)
  camera.position.set(0, 0, 100)
  camera.lookAt(scene.position)

  const mesh = createFontFromGeometry()
  scene.add(mesh)

  update((time: number) => {
    const angle = time / 1000
    mesh.rotation.set(angle, angle, 0)
  })

  function updateMeshs () {
    generateGeometry(mesh)
  }

  // 文字的大小
  gui.add(data, 'size', 0, 20).onChange(updateMeshs)
  // 文字的厚度
  gui.add(data, 'height', 0, 50).onChange(updateMeshs)
  // 文本曲线的分段数
  gui.add(data, 'curveSegments', 0, 30, 1).onChange(updateMeshs)
  // 是否开启斜角
  gui.add(data, 'bevelEnabled').onChange(updateMeshs)
  // 文本上斜角的深度
  gui.add(data, 'bevelThickness', 0, 50).onChange(updateMeshs)
  // 斜角与原始文本轮廓之间的延伸距离
  gui.add(data, 'bevelSize', 0, 50).onChange(updateMeshs)
  // 斜角分段数
  gui.add(data, 'bevelSegments', 0, 5).onChange(updateMeshs)
}

const data = {
  size: 10,
  height: 5,
  curveSegments: 12,
  bevelEnabled: false,
  bevelThickness: 10,
  bevelSize: 0,
  bevelSegments: 0
}

function createFontFromGeometry () {
  const loader = new FontLoader()
  const font = loader.parse(fontTyoe)
  const mesh = new THREE.Mesh()
  const geometry = new TextGeometry('Hello three.js!', {
    font,
    ...data
  })
  geometry.computeBoundingBox()
  mesh.geometry = geometry
  mesh.material = new MeshNormalMaterial()
  return mesh
}

function generateGeometry (mesh: THREE.Mesh) {
  const loader = new FontLoader()
  const font = loader.parse(fontTyoe)
  const geometry = new TextGeometry('Hello three.js!', {
    font,
    ...data
  })
  geometry.computeBoundingBox()
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createTextGeometry
}
